
from hashlib import md5

import requests



class Verify:
    def __init__(self, username, password, soft_id):
        """
        :param username: 超级鹰的用户名
        :param password: 密码
        :param soft_id: 软件id
        """
        self.username = username
        # md5加密
        password = password.encode('utf8')
        self.password = md5(password).hexdigest()
        self.soft_id = soft_id
        self.base_params = {
            'user': self.username,
            'pass2': self.password,
            'softid': self.soft_id,
        }
        self.headers = {
            'Connection': 'Keep-Alive',
            'User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        }

    def get_verify(self, im, codetype='1902'):
        """
        im: 二进制图片
        codetype: 题目类型 参考 http://www.chaojiying.com/price.html
        """
        # 打开图片为二进制
        im = open(im, 'rb').read()
        params = {
            'codetype': codetype,
        }
        params.update(self.base_params)
        files = {'userfile': ('ccc.jpg', im)}
        r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files,
                          headers=self.headers)
        print(r.json())
        try:
            verify = r.json().get('pic_str')
        except Exception as e:
            print(e.__str__())
            verify = 'None'
        return verify


if __name__ == '__main__':
    verify = Verify('testingzx', '1q2w3e4r.', '943050')  # 用户中心>>软件ID 生成一个替换 96001
    ver = verify.get_verify('a.jpg')
    print(ver)